package com.hzit.hzb.core.controller.api;


import com.alibaba.fastjson.JSON;
import com.hzit.common.result.R;
import com.hzit.hzb.base.util.JwtUtils;
import com.hzit.hzb.core.hfb.RequestHelper;
import com.hzit.hzb.core.pojo.entity.LendItem;
import com.hzit.hzb.core.pojo.vo.InvestVO;
import com.hzit.hzb.core.service.LendItemService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 标的出借记录表 前端控制器
 * </p>
 *
 * @author hbxfwf
 * @since 2024-08-27
 */
@RestController
@RequestMapping("/api/core/lendItem")
@Slf4j
public class LendItemController {

	@Autowired
	private LendItemService lendItemService;
	/**
	 * 投资
	 * @param vo
	 * @param token
	 * @return
	 */
	@PostMapping("/auth/commitInvest")
	public R commitInvest(@RequestBody InvestVO vo, @RequestHeader("token") String token){
		// 1. 获取userId
		Long userId = JwtUtils.getUserId(token);
		// 2. 获取用户名
		String userName = JwtUtils.getUserName(token);
		// 3. 将userId与userName与vo绑定
		vo.setInvestUserId(userId);
		vo.setInvestName(userName);
		// 4. 开始投资业务
		String formStr = lendItemService.commitInvest(vo);
		// 5. 返回表单串
		return R.ok().data("formStr",formStr);
	}

	/**
	 * 投标的异步咽调地址
	 * @param request
	 * @return
	 */
	@PostMapping("/notify")
	public String notify(HttpServletRequest request){
		// 1. 得到异步回调的参数
		Map<String, Object> paramMap = RequestHelper.switchMap(request.getParameterMap());
		// 2. 进行验签处理
		if (RequestHelper.isSignEquals(paramMap)) {
			String resultCode = paramMap.get("resultCode") + "";
			if("0001".equals(resultCode)){
				return lendItemService.lendItemNotify(paramMap);
			}else {
				log.info("用户投资异步回调失败：" + JSON.toJSONString(paramMap));
				return "fail";
			}
		}else{
			log.info("用户投资异步回调签名错误：" + JSON.toJSONString(paramMap));
			return "fail";
		}

	}
	/**
	 * 根据标的id查询标的项列表
	 * @param id
	 * @return
	 */
	@GetMapping("/fetchLendItemList/{id}")
	public R fetchLendItemList(@PathVariable("id") Long id){
		List<LendItem> lendItems = lendItemService.fetchLendItemList(id);
		return R.ok().data("list",lendItems);
	}
}

